package com.example.demo.config;

import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yzp
 * @date 2021/5/17 10:29
 */
@Configuration
public class DynamicDataSourceConfig {
    @Autowired
    private  HikariDataSourceProperties properties;
    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractJdbcDataSourceProvider(properties.getDriverClassName(), properties.getUrl(), properties.getUsername(), properties.getPassword()) {
            @Override
            protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
                Map<String, DataSourceProperty> map=new HashMap<>();
                ResultSet rs = statement.executeQuery(properties.getQueryDsSql());
                while (rs.next()) {
                    String name = rs.getString("name");
                    String username = rs.getString("username");
                    String password = rs.getString("password");
                    String url = rs.getString("url");
                    String driver = rs.getString("driver");
                    DataSourceProperty property = new DataSourceProperty();
                    property.setUsername(username);
                    property.setPassword(password);
                    property.setUrl(url);
                    property.setDriverClassName(driver);
                    map.put(name, property);
                }
                // 添加默认主数据源
                DataSourceProperty property = new DataSourceProperty();
                property.setUsername(properties.getUsername());
                property.setPassword(properties.getPassword());
                property.setUrl(properties.getUrl());
                map.put("master", property);
                return map;
            }
        };
    }
}
